package cn.crdeng.controller;

import cn.crdeng.Service.BlogService;
import cn.crdeng.Service.TagService;
import cn.crdeng.Service.TypeService;
import cn.crdeng.po.Blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class indexController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;

    /**
     * 主页
     *
     * @param pageable
     * @param model
     * @return
     */
    @GetMapping("/")
    public String index(@PageableDefault(size = 6, sort = "updateTime", direction = Sort.Direction.DESC) Pageable pageable, Model model) {
        model.addAttribute("pageInfo", blogService.listBlog(pageable));
        model.addAttribute("types", typeService.findAllType(6));
        model.addAttribute("tags", tagService.listTag());
        model.addAttribute("recommends", blogService.listRecommendBlogTop(6));
        return "index";
    }

    /**
     * 搜索
     *
     * @param query
     * @param pageable
     * @param model
     * @return
     */
    @PostMapping("/search")
    public String searchBlog(@RequestParam String query,
                             @PageableDefault(size = 5, sort = "views", direction = Sort.Direction.DESC) Pageable pageable,
                             Model model) {
        model.addAttribute("pageInfo", blogService.searchBlog(query, pageable));
        return "search";
    }

    /**
     * 跳转到关于我
     *
     * @return
     */
    @GetMapping("/me")
    public String me() {
        return "me";
    }

    /**
     * 底部栏的最新博客
     */
    @GetMapping("/footer/recommendBlog")
    public String getBotton(Model model) {
        List<Blog> blogs = blogService.listRecommendBlogTop(3);
        model.addAttribute("recommend", blogs);
        return "_fragments :: recommendBlog";
    }

}
